package com.qcby.llmtchstd.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.qcby.llmtchstd.common.ResponseResult;
import com.qcby.llmtchstd.entity.ErrorNote;
import com.qcby.llmtchstd.entity.Exam;
import com.qcby.llmtchstd.entity.IfNotExam;
import com.qcby.llmtchstd.entity.User;
import com.qcby.llmtchstd.service.ErrorNoteService;
import com.qcby.llmtchstd.utils.LLMClient;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/errornote")
public class ErrorNoteController {
    @Autowired
    private ErrorNoteService errorNoteService;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/add")
    public ResponseResult<Integer> addError(@RequestBody ErrorNote errorNote, HttpSession httpSession) {
        System.out.println("hi");
        Integer ans = errorNoteService.addError(errorNote);
        System.out.println(ans);
        if (ans != null) {
            return ResponseResult.success("插入成功", ans);
        } else {
            return ResponseResult.fail("4003", "插入失败，无数据或查询异常");
        }
    }
    @GetMapping("/select")
    public ResponseResult<List<ErrorNote>> selectAll(HttpSession httpSession) {
        User loginUser = (User)httpSession.getAttribute("loginUser");
        int id = loginUser.getId();
        List<ErrorNote> list = errorNoteService.selectAll(id);
        System.out.println("list-------------------"+list.toString());
        if (list != null) {
            return ResponseResult.success("查询成功", list);
        } else {
            return ResponseResult.fail("4003", "查询失败，无数据或查询异常");
        }
    }
    @PostMapping("/delete")
    public ResponseResult<Integer> deleteOne(int id) {

        Integer ans = errorNoteService.deleteOne(id);
        if (ans != null) {
            return ResponseResult.success(" 删除成功", ans);
        } else {
            return ResponseResult.fail("4003", "删除失败，无数据或查询异常");
        }
    }


    @PostMapping("/insert")
    public ResponseResult<Integer> add(@RequestBody Map<String, Object> requestData, HttpSession httpSession) {
        try {
            // 1. 构建提示词（替换错题列表占位符）
            String questions = requestData.get("questions").toString();
            String prompt = String.format(
                    "请根据我提供的错题列表，为我重新生成一套配套的模拟试卷。具体要求如下：\n" +
                            "\n" +
                            "一、试卷结构（必须包含以下所有题型，允许部分题型为空）：\n" +
                            "1. 选择题：包含题干、分值、选项列表（至少3个选项）、正确答案\n" +
                            "2. 填空题：包含题干、分值、正确答案\n" +
                            "3. 判断题：包含题干、分值、正确答案（true/false）、解析（可选）\n" +
                            "4. 简答题：包含题干、分值、参考答案\n" +
                            "5. 计算题：包含题干、分值、答案、解题步骤（若无法生成则返回空数组）\n" +
                            "\n" +
                            "二、题目数量与分值：\n" +
                            "- 总题量根据错题数量合理分配，不宜过多或过少\n" +
                            "- 各题型分值自定，但需保证总分合理\n" +
                            "- 单题分值建议：选择/填空/判断 2-5分，简答 5-10分，计算 5-15分\n" +
                            "\n" +
                            "三、格式要求（严格遵守，否则视为无效）：\n" +
                            "1. 仅返回符合以下结构的JSON字符串，不包含任何其他内容（包括解释、说明、前缀文字等）。\n" +
                            "2. JSON字段必须与示例完全一致，不得增减字段或修改字段名。\n" +
                            "{\n" +
                            "  \"examName\": \"试卷标题\",\n" +
                            "  \"description\": \"试卷说明\",\n" +
                            "  \"choiceQuestions\": [\n" +
                            "    {\"id\": 题号, \"content\": \"题干\", \"score\": 分值, \"options\": [\"选项A\"...], \"answer\": \"正确选项\"}\n" +
                            "  ],\n" +
                            "  \"fillQuestions\": [\n" +
                            "    {\"id\": 题号, \"content\": \"题干\", \"score\": 分值, \"answer\": \"答案\"}\n" +
                            "  ],\n" +
                            "  \"judgeQuestions\": [\n" +
                            "    {\"id\": 题号, \"content\": \"题干\", \"score\": 分值, \"answer\": \"true/false\", \"analysis\": \"解析\"}\n" +
                            "  ],\n" +
                            "  \"essayQuestions\": [\n" +
                            "    {\"id\": 题号, \"content\": \"题干\", \"score\": 分值, \"answer\": \"参考答案\"}\n" +
                            "  ],\n" +
                            "  \"calculateQuestions\": [\n" +
                            "    {\"id\": 题号, \"content\": \"题干\", \"score\": 分值, \"answer\": \"答案\", \"steps\": [\"步骤1\"...]}\n" +
                            "  ]\n" +
                            "}\n" +
                            "\n" +
                            "四、内容要求：\n" +
                            "1. 题目需与错题涉及的知识点高度相关\n" +
                            "2. 难度与错题难度匹配，避免超纲内容\n" +
                            "3. 确保答案准确无误，计算题步骤清晰\n" +
                            "4. 避免与原错题完全重复\n" +
                            "\n",
                    questions  // 替换%s为实际错题列表
            );

            // 2. 调用LLM获取响应
            String llmResponse = LLMClient.getLLMResponse2(questions, prompt);
            System.out.println("--------------------------------------------------");
            // 3. 解析LLM响应，提取核心试卷JSON
            Gson gson = new Gson();
            JsonNode aiReply = parseLLMResponse(llmResponse);  // 确保此方法正确提取content
            System.out.println(aiReply);

            // 4. 手动构建Exam对象（适配String类型字段）
            Exam exam = new Exam();

            // 4.1 设置数组字段（转为JSON字符串）
            if (aiReply.has("choiceQuestions")) {
                exam.setChoiceQuestions(aiReply.get("choiceQuestions").toString());
            }
            if (aiReply.has("fillQuestions")) {
                exam.setFillQuestions(aiReply.get("fillQuestions").toString());
            }
            if (aiReply.has("judgeQuestions")) {
                exam.setJudgeQuestions(aiReply.get("judgeQuestions").toString());
            }
            if (aiReply.has("essayQuestions")) {
                exam.setEssayQuestions(aiReply.get("essayQuestions").toString());
            }
            if (aiReply.has("calculateQuestions")) {
                exam.setCalculateQuestions(aiReply.get("calculateQuestions").toString());
            }

            // 4.2 设置基本字段
            if (aiReply.has("examName")) {
                exam.setExamName(aiReply.get("examName").asText());
            }
            if (aiReply.has("description")) {
                exam.setDescription(aiReply.get("description").asText());
            }

            // 5. 设置创建者信息
            User loginUser = (User) httpSession.getAttribute("loginUser");
            exam.setCreatorId(loginUser.getId());
            exam.setCreatorType(0);
            Integer  examDuration = (Integer) requestData.get("exam_duration");
            System.out.println("examDuration:"+examDuration);
            exam.setExamDuration(examDuration);
            String releaseTimeStr = (String) requestData.get("release_time");
            if (releaseTimeStr == null || releaseTimeStr.trim().isEmpty()) {
                // 处理空值（如抛异常或设默认值）
                throw new IllegalArgumentException("release_time不能为空");
            }

// 2. 解析为LocalDateTime（使用ISO格式器，支持2025-08-07T08:36这种格式）
            LocalDateTime releaseTime = LocalDateTime.parse(
                    releaseTimeStr,
                    DateTimeFormatter.ISO_LOCAL_DATE_TIME  // 内置格式器，适配带T的日期时间
            );

// 3. 赋值给exam对象
            exam.setReleaseTime(releaseTime);
            // 6. 保存到数据库
            System.out.println("exam:---------"+exam);
            Integer ans = errorNoteService.add(exam);
            return ResponseResult.success("添加成功", ans);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("500", "添加失败：" + e.getMessage());
        }
    }
    private JsonNode parseLLMResponse(String llmResponse) {
        try {
            // 解析原始JSON响应
            JsonNode rootNode = objectMapper.readTree(llmResponse);

            // 根据Deepseek API的响应结构，提取choices中的content
            if (rootNode.has("choices") && rootNode.get("choices").isArray() &&
                    rootNode.get("choices").size() > 0) {

                JsonNode contentNode = rootNode.get("choices").get(0).get("message").get("content");
                // 解析AI返回的内容（因为AI返回的是JSON格式的字符串）
                return objectMapper.readTree(contentNode.asText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
